import { memo } from 'react';
import { Navigate, RouteObject, useRoutes } from 'react-router-dom';
import Login from '../view/login';
import { RouteItem } from './Type';

const routerStor = ['home', 'cesium', 'error'];

const dynamicRouters = () => {
    const metaRouters = require.context('./modules', true, /\.tsx$/);
    const routerList: RouteItem[] = [];
    routerStor.forEach(async (key) => {
        const routers = metaRouters('./' + key + '.tsx');
        routerList.push(...routers.default);
    });
    return routerList;
};

export const routerArray: RouteItem[] = dynamicRouters();

export const rootRouter: RouteItem[] = [
    {
        path: '/',
        element: <Navigate to="/login" />,
    },
    {
        path: '/login',
        element: <Login />,
        meta: {
            requiresAuth: false,
            title: '登录页',
            key: 'login',
        },
    },
    ...routerArray,
    {
        path: '*',
        element: <Navigate to="/404" />,
    },
];

const createRooters = (routers: RouteItem[]): RouteObject[] => {
    return routers.map((item) => {
        return {
            path: item.path,
            element: item.element,
            children: item.children ? createRooters(item.children) : [],
        };
    });
};

const Routers = () => {
    const routers = useRoutes(createRooters(rootRouter));
    return routers;
};

export default memo(Routers);
